import React from 'react';
import { history, connect } from 'umi';
import { Form, Button, Table, Card, Input, Divider, Modal, Radio, message, Tag } from 'antd';
import { formatMessage } from 'umi';
import moment from 'moment';
import { get as _get } from 'object-path';
import LinkTo from '@/components/LinkTo';
import AuthCode from '@/utils/auth/AuthCode';
import authHelper from '@/utils/auth/helper';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { withRoutePage } from '@/utils/enhanceUtils';
import routerReplace from '@/utils/routerReplace';
import Pagination from '@/components/Pagination';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import styles from './NewsManage.less';

const { checkCode } = authHelper;
const ORDER_MAP = { ASC: 'ascend', DESC: 'descend' };

@withRoutePage
@connect(({ newsManage, loading }) => ({
    newsManage,
    loading: loading.models.newsManage
}))
@Form.create()
class NewsList extends React.PureComponent {
    columns = [
        {
            title: '新闻标题',
            dataIndex: 'newsCnName',
            width: 300,
            render: (text, record) => (
                <div style={{ maxWidth: 268, position: 'relative' }}>
                    <p
                        style={{
                            cursor: 'pointer',
                            fontWeight: 'bold',
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            marginBottom: '8px'
                        }}
                    >
                        {' '}
                        {record.topping === 0 ? (
                            <Tag style={{ marginRight: '4px' }} color="red">
                                置顶
                            </Tag>
                        ) : (
                            ''
                        )}
                        <LinkTo
                            className={styles.LinkTo}
                            disabled={!checkCode(this.authCode('detail'))}
                            title={record.newsCnName}
                            to="/office/info/webSite/newsList/newsEdit"
                            query={{
                                code: record.newsCode,
                                id: record.id,
                                isEdit: record.isEdit
                            }}
                        >
                            {record.newsCnName}
                        </LinkTo>
                    </p>
                    <p
                        style={{
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            fontSize: '12px',
                            color: 'rgba(0,0,0,0.45)'
                        }}
                    >
                        {record.briefContentCn}
                    </p>
                </div>
            )
        },
        {
            title: '发布时间',
            dataIndex: 'releaseTime',
            width: 200,
            sorter: () => {},
            render: (text, record) => <span>{moment(record.releaseTime).format('YYYY-MM-DD HH:mm')}</span>
        },
        {
            title: '发布人',
            dataIndex: 'createUser'
        },
        {
            title: '新闻类别',
            dataIndex: 'newsTypesName'
        },
        {
            title: '隐藏新闻',
            width: 100,
            dataIndex: 'hidden',
            render: text => {
                if (text === 0) {
                    return <span title="此职位为隐藏状态，不在官网新闻列表显示">是</span>;
                }
                return <span>否</span>;
            }
        },
        {
            title: formatMessage({ id: 'columns.orgList.action' }),
            width: 200,
            fixed: 'right',
            render: (text, record) => (
                <span>
                    {record.topping === 0 ? (
                        <a
                            href="#"
                            style={{ color: '#FFD38C', cursor: 'default' }}
                            disabled={!checkCode(this.authCode('edit'))}
                        >
                            设置
                        </a>
                    ) : (
                        <a
                            href="#"
                            onClick={e => {
                                e.preventDefault();
                                this.setState({
                                    newsCode: record.newsCode,
                                    id: record.id
                                });
                                const { form } = this.props;
                                form.setFieldsValue({
                                    hidden: record.hidden
                                });
                                this.showModal();
                            }}
                            style={{
                                cursor: this.isAuthEdit ? 'pointer' : 'default'
                            }}
                            disabled={!checkCode(this.authCode('edit'))}
                        >
                            设置
                        </a>
                    )}
                    <Divider type="vertical" />
                    <LinkTo
                        disabled={!checkCode(this.authCode('detail'))}
                        title={record.newsCnName}
                        to="/office/info/webSite/newsList/newsEdit"
                        query={{
                            code: record.newsCode,
                            id: record.id,
                            isEdit: record.isEdit
                        }}
                    >
                        详情
                    </LinkTo>
                    <Divider type="vertical" />
                    {record.topping === 0 ? (
                        <a
                            href=" javascript:;"
                            style={{
                                color: record.hidden === 0 ? '#FFD38C' : '#FFA22D',
                                cursor: record.hidden === 0 ? 'default' : 'pointer'
                            }}
                            disabled={!checkCode(this.authCode('top'))}
                            onClick={() => {
                                if (record.hidden === 0) {
                                    return;
                                }
                                this.handleTop(record.newsCode, record.id);
                            }}
                        >
                            {record.hidden === 0 ? '置顶' : '取消置顶'}
                        </a>
                    ) : (
                        <a
                            href=" javascript:;"
                            style={{
                                color: record.hidden === 0 ? '#FFD38C' : '#FFA22D',
                                cursor: record.hidden === 0 ? 'default' : 'pointer'
                            }}
                            disabled={!checkCode(this.authCode('top'))}
                            onClick={() => {
                                if (record.hidden === 0) {
                                    return;
                                }
                                this.handleTop(record.newsCode, record.id);
                            }}
                        >
                            置顶
                        </a>
                    )}
                </span>
            )
        }
    ];

    constructor(props) {
        super(props);
        const {
            location: { query }
        } = this.props;
        this.state = {
            visible: false,
            sorterField: query.sort,
            sorterInfo: {},
            newsCode: '',
            id: null,
            isLoading: false
        };

        this.authCode = new AuthCode(props.route.code).authCode;
        this.isAuthEdit = checkCode(this.authCode('edit'));
    }

    componentDidMount() {
        const {
            location: { query },
            form
        } = this.props;
        form.setFieldsValue(query);
        this.columns[1].sortOrder = ORDER_MAP[query.sort];
        this.handleSearch();
    }

    componentWillUnmount() {
        const { dispatch } = this.props;
        dispatch({
            type: 'newsManage/save',
            payload: {
                paginationNews: {
                    pageSize: 10,
                    current: 1,
                    total: 0
                }
            }
        });
    }

    handleSearch = () => {
        const {
            dispatch,
            form,
            newsManage: { paginationNews }
        } = this.props;
        form.validateFieldsAndScroll((err, fieldsValue) => {
            if (err) return;
            const sort = (() => {
                if (!this.state.sorterField) return '';
                return this.state.sorterField.split('end')[0].toUpperCase();
            })();
            const payload = {
                keyword: fieldsValue.keyword,
                sort,
                pageNo: paginationNews.current,
                pageSize: paginationNews.pageSize
            };
            routerReplace({ query: payload });
            dispatch({
                type: 'newsManage/fetchNewsList',
                payload
            });
        });
    };

    handleSubmit = async e => {
        e.preventDefault();
        const { dispatch } = this.props;
        await dispatch({
            type: 'newsManage/save',
            payload: {
                paginationNews: {
                    pageSize: 10,
                    current: 1
                }
            }
        });
        this.handleSearch();
    };

    // 编辑新闻
    createOrEditNews = async () => {
        this.setState({
            isLoading: true
        });
        const { workFlowUrl } = await hasWorkFlowByType('NewsApply'); // 检查是否有该流程
        if (workFlowUrl) {
            history.push(workFlowUrl);
        } else {
            message.warning('发布新闻的流程不存在!');
        }
        this.setState({
            isLoading: false
        });
    };

    // 排序功能
    changeTable = async (pagination, filters, sorter = {}) => {
        const { sorterInfo } = this.state;
        const extra = {};
        if (sorterInfo !== sorter) {
            extra.current = 1;
            this.setState({
                sorterInfo: sorter
            });
        }
        this.setState({
            sorterField: sorter.order
        });
        this.columns[1].sortOrder = sorter.order;
        const { dispatch, newsManage } = this.props;
        await dispatch({
            type: 'newsManage/save',
            payload: {
                paginationNews: {
                    ...newsManage.paginationNews,
                    ...pagination,
                    ...extra
                }
            }
        });
        this.handleSearch();
    };

    showModal = () => {
        this.setState({
            visible: true
        });
    };

    handleOk = () => {
        const { dispatch, form } = this.props;
        form.validateFieldsAndScroll((err, fieldsValue) => {
            if (err) return;
            dispatch({
                type: 'newsManage/fetchNewsHide',
                payload: {
                    code: _get(this.state, 'newsCode'),
                    id: _get(this.state, 'id'),
                    hidden: fieldsValue.hidden
                },
                callback: res => {
                    if (res.code === 10000) {
                        message.success(res.msg);
                        this.handleSearch();
                    } else {
                        message.error(res.msg);
                    }
                }
            });
        });
        this.setState({
            visible: false
        });
    };

    handleTop = (newsCode, id) => {
        const { dispatch, form } = this.props;
        form.validateFieldsAndScroll(err => {
            if (err) return;
            dispatch({
                type: 'newsManage/fetchNewsSort',
                payload: {
                    code: newsCode,
                    id
                },
                callback: res => {
                    if (res.code === 10000) {
                        message.success(res.msg);
                        this.handleSearch();
                    } else {
                        message.error(res.msg);
                    }
                }
            });
        });
    };

    handleCancel = () => {
        this.setState({
            visible: false
        });
    };

    render() {
        const {
            loading,
            form: { getFieldDecorator },
            newsManage: { data, paginationNews }
        } = this.props;
        const { visible, isLoading, sorterInfo } = this.state;

        return (
            <PageHeaderWrapper>
                <Card
                    bordered={false}
                    className={styles.bodynopading}
                    title="新闻管理"
                    extra={
                        <Button
                            disabled={!checkCode(this.authCode('add'))}
                            type="primary"
                            onClick={this.createOrEditNews}
                            loading={isLoading}
                        >
                            发起新闻
                        </Button>
                    }
                >
                    <Form layout="inline" onSubmit={this.handleSubmit}>
                        <Form.Item>
                            {getFieldDecorator('keyword', {
                                initialValue: ''
                            })(
                                <Input
                                    placeholder="输入关键词搜索更多新闻"
                                    enterButton={formatMessage({
                                        id: 'btn.orgList.search'
                                    })}
                                    style={{ width: 248 }}
                                    allowClear
                                    // suffix={
                                    //     <Icon
                                    //         type="search"
                                    //         style={{
                                    //             color: 'rgba(0,0,0,0.15)'
                                    //         }}
                                    //     />
                                    // }
                                />
                            )}
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                {formatMessage({
                                    id: 'edit.search.btn'
                                })}
                            </Button>
                        </Form.Item>
                    </Form>
                    <Table
                        style={{ marginTop: '24px' }}
                        rowKey="id"
                        loading={loading}
                        dataSource={data}
                        onChange={this.changeTable}
                        columns={this.columns}
                        pagination={false}
                        scroll={{ x: 'max-content' }}
                    />
                    <Pagination {...paginationNews} onChange={this.changeTable} sorter={sorterInfo} loading={loading} />
                </Card>
                <Modal title="新闻设置" visible={visible} onOk={this.handleOk} onCancel={this.handleCancel}>
                    <Form layout="inline">
                        <Form.Item label="是否隐藏新闻：">
                            <div>
                                {getFieldDecorator('hidden', {
                                    initialValue: 1,
                                    rules: [
                                        {
                                            required: true
                                        }
                                    ]
                                })(
                                    <Radio.Group onChange={this.onChange}>
                                        <Radio value={0}>是</Radio>
                                        <Radio value={1}>否</Radio>
                                    </Radio.Group>
                                )}
                                <p className={styles.modalLabel}>
                                    （隐藏的新闻不在官网新闻列表中显示，也不可置顶操作）
                                </p>
                            </div>
                        </Form.Item>
                    </Form>
                </Modal>
            </PageHeaderWrapper>
        );
    }
}
export default NewsList;
